import store from "@/store/index.js";
import router from "../router/index.js";
import storage from "./storage";

router.beforeEach((to, from, next) => {
  let token = storage.get("token");
  if (token) {
    // if (store.state.auths.menus.length <= 0) {
    //   store.dispatch("auths/FETCH_MENUS");
    // }
    // next();
    if (!store.state.auths.menus.length) {
      console.log(store.state.auths.menus);
      //发起请求,获取远程菜单
      store.dispatch("auths/FETCH_MENUS").then(() => {
        console.log(to);
        // if (to.path === "/") {
        //   to.path === "/welcome";
        // }
        //这里要注意, next里面要传参数即要进入的页面的路由信息，因为next传参数后，当前要进入的路由会被废止，转而进入参数对应的路由，虽然是同一个路由，这么做主要是为了确保addRoute生效了,并且不产生历史记录
        next({ path: to.redirectedFrom, replace: true });
      });
    } else {
      next();
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      next({ path: "/login" });
    }
  }
});

export default router;
